package com.dhcc.bpm.modules.scf.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhcc.bpm.common.segmentId.LocalCacheIdGenerator;
import com.dhcc.bpm.common.utils.StringUtils;
import com.dhcc.bpm.modules.scf.dto.ScfInvoiceInfoDTO;
import com.dhcc.bpm.modules.scf.entity.HomePage.Aggregate.InvoiceInfo;
import com.dhcc.bpm.modules.scf.entity.ScfInvoiceInfo;
import com.dhcc.bpm.modules.scf.entity.ScfOperationLogInfo;
import com.dhcc.bpm.modules.scf.entity.SelectEntity.InvoiceInfoPaymentInfoRef;
import com.dhcc.bpm.modules.scf.entity.SelectEntity.RecyclingInByPayment;
import com.dhcc.bpm.modules.scf.enumUtil.ScfOperationLogInfoEnum;
import com.dhcc.bpm.modules.scf.mapper.ScfInvoiceInfoMapper;
import com.dhcc.bpm.modules.scf.mapper.ScfPaymentInfoMapper;
import com.dhcc.bpm.modules.scf.service.IScfFileAttachmentInfoService;
import com.dhcc.bpm.modules.scf.service.IScfInvoiceInfoService;
import com.dhcc.bpm.modules.scf.service.IScfOperationLogInfoService;
import com.dhcc.bpm.modules.scf.util.ExcelUtil;
import com.dhcc.bpm.modules.scf.util.MD5Utils;
import com.dhcc.bpm.modules.scf.util.OBSUtil;
import com.dhcc.bpm.modules.scf.util.StringUtil;
import com.dhcc.bpm.modules.scf.vo.ScfFileAttachmentInfoVO.ScfFileAttachmentInfoVO;
import com.dhcc.bpm.modules.scf.vo.ScfInvoiceInfoVO.ScfGetInvoiceDetailsVO;
import com.dhcc.bpm.modules.scf.vo.ScfInvoiceInfoVO.ScfGetInvoiceListVO;
import com.dhcc.bpm.modules.scf.vo.ScfPaymentInfoVO.ScfGetPaymentDetailsVO;
import com.dhcc.bpm.modules.scf.vo.ScfPaymentInfoVO.ScfGetPaymentListVO;
import com.dhcc.bpm.modules.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 发票信息表 服务实现类
 */
@Service
@Slf4j
public class ScfInvoiceInfoServiceImpl extends ServiceImpl<ScfInvoiceInfoMapper, ScfInvoiceInfo> implements IScfInvoiceInfoService {
    /**
     * 文件附件service接口
     */
    @Autowired
    private IScfFileAttachmentInfoService scfFileAttachmentInfoService;
    /**
     * id生成器
     */
    @Autowired
    private LocalCacheIdGenerator localCacheIdGenerator;
    /**
     * 操作日志service接口
     */
    @Autowired
    private IScfOperationLogInfoService scfOperationLogInfoService;
    /**
     * 支付回单信息接口
     */
    @Autowired
    private ScfPaymentInfoMapper scfPaymentInfoMapper;

    @Autowired
    private ScfInvoiceInfoMapper scfInvoiceInfoMapper;
    /**
     * 用户信息接口
     */
    @Autowired
    private IUserService userService;
    /**
     * obs对象存储工具类
     */
    @Autowired
    private OBSUtil obsUtil;


    /**
     * 自定义分页查询
     *
     * @param page
     * @param scfInvoiceInfo
     * @return
     */
    @Override
    public IPage<ScfGetInvoiceListVO> selectScfInvoiceInfoPage(IPage<ScfGetInvoiceListVO> page, ScfInvoiceInfoDTO scfInvoiceInfo) {
        // 根据分页参数查询发票信息列表
        List<ScfGetInvoiceListVO> scfGetInvoiceListVOS = baseMapper.selectScfInvoiceInfoPage(page, scfInvoiceInfo);
        // 如果发票信息列表有记录则继续
        if (scfGetInvoiceListVOS.size() != 0) {
            for (ScfGetInvoiceListVO scfGetInvoiceListVO : scfGetInvoiceListVOS) {
                // 根据用户id查询用户名称，重新赋值登记人字段
                List<Long> ids = new ArrayList<>();
                ids.add(Long.valueOf(scfGetInvoiceListVO.getRecorder()));
                scfGetInvoiceListVO.setRecorder(userService.selectUserNameByIds(ids).get(0));

                // 查询发票信息与支付回单的关联关系, 设置发票单的关联属性
                // 根据发票单号查询关联表
                List<String> invoicePaymentRowId = baseMapper.selectRowIdByInvoiceRowId(scfGetInvoiceListVO.getRowId());
                if (invoicePaymentRowId != null && !invoicePaymentRowId.isEmpty()) {
                    // 设置返回的关联属性为已关联
                    scfGetInvoiceListVO.setAssociationSts("1");
                } else {
                    // 设置返回的关联属性为未关联
                    scfGetInvoiceListVO.setAssociationSts("0");
                }

            }
        }
        // 返回重新赋值了登记人字段的分页查询列表
        return page.setRecords(scfGetInvoiceListVOS);
    }

    /**
     * 查看详情
     *
     * @param scfInvoiceInfo
     * @return
     */
    @Override
    public ScfGetInvoiceDetailsVO details(ScfInvoiceInfoDTO scfInvoiceInfo) {
        // 查询指定RowId主键的发票详情信息
        ScfGetInvoiceDetailsVO detail = baseMapper.getDeatil(scfInvoiceInfo.getRowId());
        if (detail != null) {
            // 获取与文件附件表关联的id
            String rowId = detail.getRowId();
            // 查询关联的附件信息
            List<ScfFileAttachmentInfoVO> scfFileAttachmentInfoVOS = scfFileAttachmentInfoService.selectAllByAssociationId(rowId);
            // 详情信息中补充文件附件数据
            detail.setFileAttachmentInfoVOS(scfFileAttachmentInfoVOS);
            // 根据用户id查询用户名称，重新赋值登记人字段

            //根据完税rowid 找到 支付单号paynum
            List<ScfGetPaymentListVO> scfGetPaymentListVOS = scfPaymentInfoMapper.queryScfGetPaymentListVOByInvoiceRowId(scfInvoiceInfo.getRowId());
            if (scfGetPaymentListVOS != null && !scfGetPaymentListVOS.isEmpty()) {
                for (ScfGetPaymentListVO scfGetPaymentListVO : scfGetPaymentListVOS) {
                    scfGetPaymentListVO.setRemainingAmount(scfGetPaymentListVO.getAmount().subtract(new BigDecimal(scfGetPaymentListVO.getUseAmount())));
                }
            }
            detail.setScfGetPaymentListVOs(scfGetPaymentListVOS);
            List<Long> ids = new ArrayList<>();
            ids.add(Long.valueOf(detail.getRecorder()));
            detail.setRecorder(userService.selectUserNameByIds(ids).get(0));
        }
        return detail;
    }

    /**
     * 新增发票信息
     *
     * @param scfInvoiceInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveInvoiceInfo(ScfInvoiceInfoDTO scfInvoiceInfo) throws Exception {
        // 录入开始首先判断该发票是否已录入
        if (baseMapper.selectRowIdByInvoiceNum(scfInvoiceInfo.getInvoiceNum()) != null) {
            // 根据发票号码查询到了对应的记录rowId--则认为该发票已录入
            throw new Exception("发票：" + scfInvoiceInfo.getInvoiceNum() + "已录入，请勿重复录入！");
        }
        // 生成日期
        SimpleDateFormat date = new SimpleDateFormat("YYYYMMdd");
        String formatdate = date.format(new Date());
        // 生成时间
        SimpleDateFormat timeFormat = new SimpleDateFormat("HHmmss");
        String formTime = timeFormat.format(new Date());
        // 获取当前年月日时分秒
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String recordTime = dateFormat.format(calendar.getTime());
        // 设置记录编号
        // 生成ROW_ID

        String rowId = "FP" + MD5Utils.md5(scfInvoiceInfo.getInvoiceNum());
        scfInvoiceInfo.setRowId(rowId);
        // 设置默认关联状态未0
        scfInvoiceInfo.setAssociationSts("0");
        // 设置关联状态-通过获取发票记录中对应的支付回单流水号查询对应的支付回单表，如果未获取到支付回单号则认为录入时并未填写支付回单号
        String paymentNum = scfInvoiceInfo.getPaymentNum();
        if (paymentNum == null) {
            // 无关联编号时默认为未关联：0
            scfInvoiceInfo.setAssociationSts("0");
        } else {
            // 在支付回单表中查询对应的支付回单号是否存在
            String withInvoice = scfPaymentInfoMapper.isWithInvoice(paymentNum);
            if (withInvoice != null) {
                scfInvoiceInfo.setAssociationSts("1");
            }
            // 开始查询当前新增的发票是否关联了支付回单-同步更新支付回单中的部分字段
            ScfGetPaymentDetailsVO detail = scfPaymentInfoMapper.getDetail(scfPaymentInfoMapper.selectRowIdBypaymentNum(paymentNum));
            // 获取到支付回单的面值
            BigDecimal payAmount = detail.getAmount();


            // 获取到当前发票的面值
            BigDecimal InvoicetotalAmount = scfInvoiceInfo.getTotalAmount();
            // 计算关联状态
            BigDecimal remainingAmount = payAmount.subtract(InvoicetotalAmount);
            // 判断关联状态
            // 支付回单面值减去发票面值，如果减完剩余金额=支付回单面值则认为暂未关联发票=0
            // 支付回单面值减去发票面值，如果减完剩余金额=0则认为发票已全部关联=2
            // 支付回单面值减去发票面值，如果减完剩余金额=小于支付回单面值，但是大于发票面值则认为发票部分关联=1
            if (remainingAmount.compareTo(BigDecimal.ZERO) == 0) {
                // 发票已全部关联
                detail.setIsWithInvoice("2");
            } else if (remainingAmount.compareTo(payAmount) == 0) {
                // 暂未关联发票
                detail.setIsWithInvoice("0");
            } else if (remainingAmount.compareTo(BigDecimal.ZERO) > 0 && remainingAmount.compareTo(InvoicetotalAmount) > 0) {
                // 发票部分关联
                detail.setIsWithInvoice("1");
            }
            // 更新支付回单
            scfPaymentInfoMapper.updateById(detail);

        }


        // 设置登记日期
        scfInvoiceInfo.setRecordDate(formatdate);
        // 设置登记时间
        scfInvoiceInfo.setRecordTime(formTime);
        // 补充字段结束
        List<String> rowIds = scfInvoiceInfo.getRowIds();
        // 设置完税发票文件存放路径
        String path = "FP" + "/" + rowId + "/";
        if (rowId != null) {
            if (rowIds != null && !rowIds.isEmpty()) {
                // 取消旧文件与记录关联
                scfFileAttachmentInfoService.updataFiledNull(rowId);
                // 给上传的新文件添加关联编号
                scfFileAttachmentInfoService.batchUpdateField(rowIds, rowId);
                for (String fileRowId : rowIds) {
                    // 根据文件id获取文件的临时objectKey
                    String objectKeyOfTemp = scfFileAttachmentInfoService.getFilePath(fileRowId, null);
                    // 截取文件的名称
                    String extractFileName = obsUtil.extractFileName(objectKeyOfTemp);
                    // 拼接正式的objectKey
                    String objectKey = path + extractFileName;
                    obsUtil.copyFile(objectKey, objectKeyOfTemp);
                    scfFileAttachmentInfoService.updateFilePath(fileRowId, objectKey);
                }
            }
        }
        // 存入数据库中
        boolean save = save(scfInvoiceInfo);
        // 记录操作日志
        ScfOperationLogInfo scfOperationLogInfo = new ScfOperationLogInfo();
        // 根据用户id查询用户名称，重新赋值登记人字段
        List<Long> ids = new ArrayList<>();
        ids.add(Long.valueOf(scfInvoiceInfo.getRecorder()));
        scfOperationLogInfo.setRecorder(userService.selectUserNameByIds(ids).get(0));
        scfOperationLogInfo.setOperationModule(ScfOperationLogInfoEnum.INVOICE.getOperation());
        scfOperationLogInfo.setOperationFunction("完税信息维护");
        scfOperationLogInfo.setOperationType(ScfOperationLogInfoEnum.ADD.getOperation());
        scfOperationLogInfo.setOperationContent("新增一条发票信息，发票号码：" + scfInvoiceInfo.getInvoiceNum());
        scfOperationLogInfo.setRecordDate(recordTime);
        // 如果发票信息存储成功后则记录操作日志
        if (save) {
            scfOperationLogInfoService.saveOperationLogInfo(scfOperationLogInfo);
        }
        return save;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int bachSaveInvoiceInfo(List<ScfInvoiceInfo> scfInvoiceInfos, String operatorId) {
        List<ScfInvoiceInfo> scfInvoiceInfoList = new ArrayList<>();
        List<ScfOperationLogInfo> scfOperationLogInfoList = new ArrayList<>();
        for (ScfInvoiceInfo scfInvoiceInfo : scfInvoiceInfos) {
            // 设置登记人ID
            scfInvoiceInfo.setRecorder(operatorId);
            // 设置发票号码和发票代码
            String invoiceNum = scfInvoiceInfo.getInvoiceNum();
            // 如果发票号码大于12位，则拆数字
            if (invoiceNum.length() > 12) {
                scfInvoiceInfo.setInvoiceCode(invoiceNum.substring(0, 12));
                scfInvoiceInfo.setInvoiceNum(invoiceNum.substring(invoiceNum.length() - 8));
            }
            // 设置发票默认关联状态为0未关联到支付回单
            scfInvoiceInfo.setAssociationSts("0");
            // 发票类别
            String invoiceType = scfInvoiceInfo.getInvoiceType();
            if (invoiceType != null) {
                switch (invoiceType) {
                    case "供销发票":
                        // 执行与 value1 匹配的代码块
                        scfInvoiceInfo.setInvoiceType("1");
                        break;
                    case "采购发票":
                        // 执行与 value2 匹配的代码块
                        scfInvoiceInfo.setInvoiceType("2");
                        break;
                    case "白条入账":
                        // 执行与 value2 匹配的代码块
                        scfInvoiceInfo.setInvoiceType("3");
                        break;
                    // 可以有更多的 case 分支
                    default:
                        // 如果没有任何 case 匹配，则执行 default 代码块
                        break;
                }
            }
            // 生成日期
            SimpleDateFormat date = new SimpleDateFormat("YYYYMMdd");
            String formatdate = date.format(new Date());
            // 生成时间
            SimpleDateFormat timeFormat = new SimpleDateFormat("HHmmss");
            String formTime = timeFormat.format(new Date());
            // 获取当前年月日时分秒
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
            String recordTime = dateFormat.format(calendar.getTime());
            // 设置记录编号
            // 生成ROW_ID
            scfInvoiceInfo.setRowId("FP" + MD5Utils.md5(scfInvoiceInfo.getInvoiceNum()));
            // 设置默认关联状态未0
            scfInvoiceInfo.setAssociationSts("0");
            // 设置关联状态-通过获取发票记录中对应的支付回单流水号查询对应的支付回单表，如果未获取到支付回单号则认为录入时并未填写支付回单号
            String paymentNum = scfInvoiceInfo.getPaymentNum();
            if (paymentNum == null) {
                // 无关联编号时默认为未关联：0
                scfInvoiceInfo.setAssociationSts("0");

            } else {

                // 开始查询当前新增的发票是否关联了支付回单-同步更新支付回单中的部分字段
                ScfGetPaymentDetailsVO detail = scfPaymentInfoMapper.getDetail(scfPaymentInfoMapper.selectRowIdBypaymentNum(paymentNum));
                if (detail != null) {
                    BigDecimal payAmount = detail.getAmount();
                    BigDecimal InvoicetotalAmount = scfInvoiceInfo.getTotalAmount();
                    BigDecimal remainingAmount = payAmount.subtract(InvoicetotalAmount);
                    if (remainingAmount.compareTo(BigDecimal.ZERO) == 0) {
                        // 发票已全部关联
                        detail.setIsWithInvoice("2");
                    } else if (remainingAmount.compareTo(payAmount) == 0) {
                        // 暂未关联发票
                        detail.setIsWithInvoice("0");
                    } else if (remainingAmount.compareTo(BigDecimal.ZERO) > 0 && remainingAmount.compareTo(InvoicetotalAmount) > 0) {
                        // 发票部分关联
                        detail.setIsWithInvoice("1");
                    }
                    scfPaymentInfoMapper.updateById(detail);
                }

                // 更新支付回单

            }


            // 设置登记日期
            scfInvoiceInfo.setRecordDate(formatdate);
            // 设置登记时间
            scfInvoiceInfo.setRecordTime(formTime);
            // 补充字段结束
            // 录入开始首先判断该发票是否已录入
            if (baseMapper.selectRowIdByInvoiceNum(scfInvoiceInfo.getInvoiceNum()) == null) {
                scfInvoiceInfoList.add(scfInvoiceInfo);
                // 记录操作日志
                ScfOperationLogInfo scfOperationLogInfo = new ScfOperationLogInfo();
                // 根据用户id查询用户名称，重新赋值登记人字段
                List<Long> ids = new ArrayList<>();
                ids.add(Long.valueOf(scfInvoiceInfo.getRecorder()));
                scfOperationLogInfo.setRecorder(userService.selectUserNameByIds(ids).get(0));
                scfOperationLogInfo.setOperationModule(ScfOperationLogInfoEnum.INVOICE.getOperation());
                scfOperationLogInfo.setOperationFunction("完税信息维护");
                scfOperationLogInfo.setOperationType(ScfOperationLogInfoEnum.ADD.getOperation());
                scfOperationLogInfo.setOperationContent("新增一条发票信息，发票号码：" + scfInvoiceInfo.getInvoiceNum());
                scfOperationLogInfo.setRecordDate(recordTime);
                scfOperationLogInfoList.add(scfOperationLogInfo);
            }
        }
        boolean saveBatch = saveBatch(scfInvoiceInfoList);
        if (saveBatch) {
            scfOperationLogInfoService.bachSaveOperationLogInfo(scfOperationLogInfoList);
        }
        return scfInvoiceInfoList.size();
    }

    /**
     * 修改发票信息
     *
     * @param scfInvoiceInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateInvoiceInfo(ScfInvoiceInfoDTO scfInvoiceInfo) {
        // 生成日期
        SimpleDateFormat date = new SimpleDateFormat("YYYYMMdd");
        String formatdate = date.format(new Date());
        // 生成时间
        SimpleDateFormat timeFormat = new SimpleDateFormat("HHmmss");
        String formTime = timeFormat.format(new Date());
        // 获取当前年月日时分秒
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String recordTime = dateFormat.format(calendar.getTime());
        String rowId = scfInvoiceInfo.getRowId();
        List<String> rowIds = scfInvoiceInfo.getRowIds();
        // 重新设置登记日期
        scfInvoiceInfo.setRecordDate(formatdate);
        // 重新设置登记时间
        scfInvoiceInfo.setRecordTime(formTime);
        // 重新设置关联状态-通过获取发票记录中对应的支付回单流水号查询对应的支付回单表，如果查询到则改为已关联状态
        String paymentNum = scfInvoiceInfo.getPaymentNum();
        if (paymentNum == null) {
            // 无关联编号时默认为未关联：0
            scfInvoiceInfo.setAssociationSts("0");
        }
        String withInvoice = scfPaymentInfoMapper.isWithInvoice(paymentNum);
        scfInvoiceInfo.setAssociationSts("0");
        if (withInvoice != null) {
            scfInvoiceInfo.setAssociationSts("1");
        }
        // 开始查询当前新增的发票是否关联了支付回单-同步更新支付回单中的部分字段
        ScfGetPaymentDetailsVO detail = scfPaymentInfoMapper.getDetail(scfPaymentInfoMapper.selectRowIdBypaymentNum(paymentNum));
        if (detail != null) {
            // 获取到支付回单的面值
            BigDecimal payAmount = detail.getAmount();
            // 获取到当前发票的面值
            BigDecimal InvoicetotalAmount = scfInvoiceInfo.getTotalAmount();
            // 计算关联状态
//            BigDecimal remainingAmount = payAmount.subtract(InvoicetotalAmount);
            BigDecimal remainingAmount = InvoicetotalAmount.subtract(payAmount);

            // 判断关联状态
            // 支付回单面值减去发票面值，如果减完剩余金额=支付回单面值则认为暂未关联发票=0
            // 支付回单面值减去发票面值，如果减完剩余金额=0则认为发票已全部关联=2
            // 支付回单面值减去发票面值，如果减完剩余金额=小于支付回单面值，但是大于发票面值则认为发票部分关联=1
            if (remainingAmount.compareTo(BigDecimal.ZERO) == 0) {
                // 发票已全部关联
                detail.setIsWithInvoice("2");
            } else if (remainingAmount.compareTo(payAmount) == 0) {
                // 暂未关联发票
                detail.setIsWithInvoice("0");
            } else if (remainingAmount.compareTo(BigDecimal.ZERO) > 0 && remainingAmount.compareTo(InvoicetotalAmount) < 0) {
                // 发票部分关联
                detail.setIsWithInvoice("1");
            }
            // 更新支付回单
            scfPaymentInfoMapper.updateById(detail);
        }

        // 设置完税发票文件存放路径
        String path = "FP" + "/" + rowId + "/";
        if (rowId != null) {
            if (rowIds != null && !rowIds.isEmpty()) {
                if (rowIds != null && rowIds.size() != 0) {
                    // 取消旧文件与记录关联
                    scfFileAttachmentInfoService.updataFiledNull(rowId);
                    // 给上传的新文件添加关联编号
                    scfFileAttachmentInfoService.batchUpdateField(rowIds, rowId);
                    for (String fileRowId : rowIds) {
                        // 根据文件id获取文件的临时objectKey
                        String objectKeyOfTemp = scfFileAttachmentInfoService.getFilePath(fileRowId, null);
                        // 截取文件的名称
                        String extractFileName = obsUtil.extractFileName(objectKeyOfTemp);
                        // 拼接正式的objectKey
                        String objectKey = path + extractFileName;
                        obsUtil.copyFile(objectKey, objectKeyOfTemp);
                        scfFileAttachmentInfoService.updateFilePath(fileRowId, objectKey);
                    }
                }
            }
        }
        // 更新表中发票信息记录
        boolean update = updateById(scfInvoiceInfo);
        // 记录操作日志
        ScfOperationLogInfo scfOperationLogInfo = new ScfOperationLogInfo();
        // 根据用户id查询用户名称，重新赋值登记人字段
        List<Long> ids = new ArrayList<>();
        ids.add(Long.valueOf(scfInvoiceInfo.getRecorder()));
        scfOperationLogInfo.setRecorder(userService.selectUserNameByIds(ids).get(0));
        scfOperationLogInfo.setOperationModule(ScfOperationLogInfoEnum.INVOICE.getOperation());
        scfOperationLogInfo.setOperationFunction("完税信息维护");
        scfOperationLogInfo.setOperationType(ScfOperationLogInfoEnum.UPDATE.getOperation());
        scfOperationLogInfo.setOperationContent("更新一条发票信息，发票号码：" + scfInvoiceInfo.getInvoiceNum());
        scfOperationLogInfo.setRecordDate(recordTime);


        // 开始关联支付回单
        List<InvoiceInfoPaymentInfoRef> invoiceInfoPaymentInfoRef = scfInvoiceInfo.getRecyclingInByPayments();
        if (invoiceInfoPaymentInfoRef != null && !invoiceInfoPaymentInfoRef.isEmpty()) {
            // 先清除旧的关联
            scfInvoiceInfoMapper.deleteByInvoiceRowId(scfInvoiceInfo.getRowId());

            // 再添加新的关联
            // 获取支付回单关联的信息
            for (InvoiceInfoPaymentInfoRef ref : invoiceInfoPaymentInfoRef) {
                if (ref.getUseAmount() == null) {
                    throw new NullPointerException("使用金额不能为空！");
                }

                // 判断使用金额
                // 获取含税总金额
                BigDecimal totalAmount = scfInvoiceInfo.getTotalAmount();
                // 获取使用金额
                BigDecimal useAmount = ref.getUseAmount();
                if (useAmount.compareTo(totalAmount) > 0) {// 使用金额大于含税总金额
                    throw new IllegalArgumentException("输入的使用金额大于发票回单总金额，请重新输入！");
                }

                if (StringUtils.isNotEmpty(ref.getRowId()) && !ref.getRowId().startsWith("WS")) {
                    ref.setPaymentRowId(ref.getRowId());
                    ref.setRowId("WS" + MD5Utils.md5(scfInvoiceInfo.getRowId() + ref.getPaymentNum()));
                }
                ref.setInvoiceNum(scfInvoiceInfo.getInvoiceNum());
                ref.setInvoiceRowId(scfInvoiceInfo.getRowId());

                ref.setOrgCode(scfInvoiceInfo.getOrgCode());
                if (StringUtils.isEmpty(ref.getPaymentRowId())) {
                    baseMapper.saveInvoiceInfoPaymentInfoRefNoPaymentRowId(ref);
                } else {
                    baseMapper.saveInvoiceInfoPaymentInfoRef(ref);
                }


            }

        } else {// 当前支付回单为空的话
            // 清空该发票与支付回单的关联关系
            // 根据发票编号查询关联表的信息
            List<String> selectRowIdByInvoiceRowId = scfInvoiceInfoMapper.selectRowIdByInvoiceRowId(scfInvoiceInfo.getRowId());
            if (selectRowIdByInvoiceRowId != null && !selectRowIdByInvoiceRowId.isEmpty()) {
                // 清空关联表信息
                for (String s : selectRowIdByInvoiceRowId) {
                    scfInvoiceInfoMapper.removeInviocePaymentByRowId(s);
                }
            }


        }


        return update;
    }

    /**
     * @param operatorId 批量导入
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public List<ScfInvoiceInfo> batchSaveScfInvoiceInfo(String operatorId, MultipartFile file) throws IOException {
        // 获取文件的Base64编码
        byte[] fileBytes = file.getBytes();
        // 解析excel文件获取数据集合
        List<ScfInvoiceInfo> scfInvoiceInfos = ExcelUtil.readExcel(fileBytes, ScfInvoiceInfo.class, "完税信息", 3);
        log.info("数据集合为：{}", scfInvoiceInfos);
        return scfInvoiceInfos;
    }

    @Override
    public Boolean deleteByIds(String[] ids) {
        return this.baseMapper.deleteByIds(ids);
    }
}
